import { createSlice } from '@reduxjs/toolkit'

export default createSlice({
  name: 'todos',
  initialState: {
    todos: JSON.parse(localStorage.getItem('todos')) || [],
  },
  reducers: {
    addTodo(state, action) {
      // 根据任务名创建任务对象
      const obj = {
        id: Date.now(),
        todoName: action.payload,
        isDone: false,
      }

      state.todos.push(obj)

      // state.todos = state.todos
    },

    updateTodo(state, action) {
      state.todos.forEach((item) => {
        if (item.id === action.payload) {
          item.isDone = !item.isDone
        }
      })
      // state.todos = state.todos
    },

    delTodo(state, action) {
      state.todos = state.todos.filter((item) => {
        return item.id !== action.payload
      })
    },

    allCheck(state, action) {
      state.todos.forEach((item) => {
        item.isDone = action.payload
      })
      // state.todos = state.todos
    },

    clearAllDone(state, action) {
      state.todos = state.todos.filter((item) => !item.isDone)
    },
  },
})
